package leetcode

import kotlinetc.println

//https://leetcode.com/problems/simplify-path/

fun main(args: Array<String>) {

    //  "/a//b////c/d//././/.."
    simplifyPath("/a/..").println()
}


//栈 的思想
/**
也可以用一个 list 装每个目录结构最后插入 / 即可，这里为了高效，用的是 StringBuilder 来一次拼接最后的结果
 */
fun simplifyPath(path: String): String {

//双指针思想，left right两个指针分别移动，截取中间的 path, 连续的 / 就后移 left 和right
    val result = ArrayList<String>()

    val slash = '/'

    val cur = "."

    val prev = ".."

    var left = 0

    var right = 1

    //add root
    result.add("/")
    var segment = StringBuffer(4)
    while (right < path.length) {

        val c = path[right]

        if (path[right] == slash || right == path.lastIndex) { // right 遇到 / 之后判断一下
            if (left + 1 == right && path[right] == slash) { //连续的 slash，就去重
                left = right
            } else {

                // /  xxx /  获取 xxx
                if (right == path.lastIndex && c != slash) segment.append(c)

                val s = segment.toString()
                when (s) {
                    prev -> { //回到上一层
                        if (result.size != 1) {
                            //移除上一层
                            result.removeAt(result.lastIndex)
                        }

                    }
                    cur -> { //当前层
                        // no op
                    }
                    else -> {
                        //下一层目录
                        result.add(s)
                    }
                }
                segment.delete(0, segment.length)
                left = right
            }
        } else segment.append(c)
        right++
    }

    val stringBuilder = StringBuilder(path.length)
    stringBuilder.append("/")
    for (j in 1 until result.size) {
        stringBuilder.append(result[j])
        if (j != result.lastIndex)
            stringBuilder.append("/")
    }

    return stringBuilder.toString()

}